package main

import (
	"context"
	"fmt"
	"go.etcd.io/etcd/clientv3"
	"time"
)

/**
etcd/clientv3:是etcd v3版本的Go语言的官方客户端
下载：
go get go.etcd.io/etcd/clientv3
github:
https://github.com/etcd-io/etcd/tree/master/clientv3

启动etcd服务：
etcd.exe
 */
func main(){
	//etcd信息配置
	cfg := clientv3.Config{
		Endpoints:[]string{"http://localhost:2379"," http://localhost:2380"},
		DialTimeout:5 * time.Second,
	}
	//获取etcd操作客户端
	cli,err := clientv3.New(cfg)
	if err!=nil{
		panic(err)
	}
	//set一个k,v到etcd
	_,err = cli.Put(context.TODO(),"name","ztind")
	if err!=nil{
		panic(err)
	}
	//get获取设置的值
	getResp,err := cli.Get(context.TODO(),"name")
	if err!=nil{
		panic(err)
	}
	fmt.Println(len(getResp.Kvs))
	fmt.Println(getResp)

	//watch监听
	wc := cli.Watch(context.TODO(),"address")
	for e := range wc {
		for _,ee := range e.Events {
			fmt.Println(ee.Type,ee.Kv,ee.PrevKv)
		}
	}

	//lease 租赁
	//lgs,err := cli.Grant(context.TODO(),20)//20s租赁有效期
	//if err!=nil{
	//	panic(err)
	//}
	////向租赁期内存值
	//_,err = cli.Put(context.TODO(),"money","100",clientv3.WithLease(lgs.ID))
	//if err!=nil{
	//	panic(err)
	//}
	//i:=0
	//for{
	//	GetResp,_ := cli.Get(context.TODO(),"money")
	//	for _,e := range GetResp.Kvs {
	//		fmt.Println(string(e.Key),string(e.Value))
	//	}
	//	time.Sleep(5 * time.Second)
	//	i +=5
	//	fmt.Printf("%d s \n",i)
	//}
	//最好用完关闭
	defer cli.Close()
}
